package com.newly.driver.mqtt.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.newly.driver.mqtt.service.MQTTReceiveCallback;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class MqttUtils {
    public static MqttClient mqttClient = null;
    private static MemoryPersistence memoryPersistence = null;
    private static MqttConnectOptions mqttConnectOptions = null;
    private static String ClientName;				//将在服务端出现的名字
//    private static String IP = "192.168.9.113";						//服务器IP
    private static String IP;						//服务器IP
    private static String userName;
    private static String passWord;


    @Value("${spring.mqtt.ip}")
    private void setIp(String ip){
        this.IP= ip;
    }
    @Value("${spring.mqtt.clientName}")
    private void setClientName(String ClientName){
        this.ClientName= ClientName;
    }
    @Value("${spring.mqtt.userName}")
    private void setUserName(String userName){
        this.userName= userName;
    }
    @Value("${spring.mqtt.passWord}")
    private void setPassWord(String passWord){
        this.passWord= passWord;
    }

    public static void mqttInit(){
        start(ClientName);
    }

    public static boolean serverIsConnected(){
        return mqttClient.isConnected();
    }

    public static void start(String clientId) {
        //初始化连接设置对象
        mqttConnectOptions = new MqttConnectOptions();
        //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
        //这里设置为true表示每次连接到服务器都以新的身份连接
        mqttConnectOptions.setCleanSession(false);
        //设置自动重连
        mqttConnectOptions.setAutomaticReconnect(true);
        //设置连接超时时间，单位是秒
        mqttConnectOptions.setConnectionTimeout(10);
        //设置持久化方式
        memoryPersistence = new MemoryPersistence();

        mqttConnectOptions.setUserName(userName);
        mqttConnectOptions.setPassword(passWord.toCharArray());
        if(null != clientId) {
            try {
                mqttClient = new MqttClient("tcp://"+IP+":1883", clientId,memoryPersistence);
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //log.info(" 连接状态："+mqttClient.isConnected());
        //设置连接和回调
        if(null != mqttClient) {
            if(!mqttClient.isConnected()) {
                //创建回调函数对象
                MQTTReceiveCallback MQTTReceiveCallback = new MQTTReceiveCallback();
                //客户端添加回调函数
                mqttClient.setCallback(MQTTReceiveCallback);
                //创建连接
                try {
                    //log.info(" 创建连接");
                    mqttClient.connect(mqttConnectOptions);
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    //log.info("连接失败");
                }

            }
        }else {
            System.out.println("mqttClient为空");
        }
        //log.info(" 连接状态"+mqttClient.isConnected());
    }

    //	关闭连接
    public static void closeConnect() {
        //关闭存储方式
        if(null != memoryPersistence) {
            try {
                memoryPersistence.close();
            } catch (MqttPersistenceException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            System.out.println("memoryPersistence is null");
        }

        //关闭连接
        if(null != mqttClient) {
            if(mqttClient.isConnected()) {
                try {
                    mqttClient.disconnect();
                    mqttClient.close();
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else {
                System.out.println("mqttClient is not connect");
            }
        }else {
            System.out.println("mqttClient is null");
        }
    }


    /**
     * 发布消息
     * @param pubTopic 订阅主题
     * @param message 返回数据
     * @param qos 服务质量
     */
    public static void publishMessage(String pubTopic, JSONObject message, int qos) {
        boolean connected = mqttClient.isConnected();
        if(null != mqttClient&& mqttClient.isConnected()) {
//            System.out.println("id:"+mqttClient.getClientId()+"发布消息   "+mqttClient.isConnected());
//            System.out.println("id:"+mqttClient.getClientId());
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setQos(qos);
            mqttMessage.setPayload(message.toString().getBytes());

            MqttTopic topic = mqttClient.getTopic(pubTopic);

            if(null != topic) {
                try {
                    MqttDeliveryToken publish = topic.publish(mqttMessage);
                    if(!publish.isComplete()) {
                        log.info("消息发布成功");
                    }
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }else {
            reConnect();
        }
    }


    //	重新连接
    public static void reConnect() {
        if(null != mqttClient) {
            if(!mqttClient.isConnected()) {
                if(null != mqttConnectOptions) {
                    // 轮循重连
                    while (true){
                        if(mqttClient.isConnected()) break;
                        try {
                            // 间隔1秒
                            Thread.sleep(1000);
                            mqttClient.connect(mqttConnectOptions);
                            //log.info(" 重连成功");
                        } catch (Exception e) {
                            //log.info(" 重连失败");
                        }
                    }
                }else {
                    log.info("mqttConnectOptions is null");
                }
            }else {
                log.info("mqttClient is null or connect");
            }
        }else {
            start(ClientName);
        }
    }

    /**
     * 订阅主题
     * @param topic 主题名
     */
    public static void subTopic(String topic) {
        if(null != mqttClient&& mqttClient.isConnected()) {
            try {
                mqttClient.subscribe(topic, 1);
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            System.out.println("mqttClient is error");
        }
    }

    /**
     * 删除订阅主题
     * @param topic 删除的主题
     */
    public static void cleanTopic(String topic) {
        if(null != mqttClient&& !mqttClient.isConnected()) {
            try {
                mqttClient.unsubscribe(topic);
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            System.out.println("mqttClient is error");
        }
    }

    /**
     * 响应消息
     * @param topic 接收主题
     * @param message 返回数据
     */
    public static void responseMessage(String topic, JSONObject message) {
        //根据接收主题修改为响应主题
        if (topic.indexOf("/message/up/message-id") >= 0) {
            topic=topic.replace("/message/up/message-id","/message/down/message-id");
        }
        else if (topic.indexOf("/command/request/request-id") >= 0) {
            topic=topic.replace("/command/request/request-id","/command/response/request-id");
        }
        //发送响应消息
        log.info(" 返回消息主题 : " + topic);
        log.info(" 返回消息内容 : " + JSONUtil.toJsonStr(message));

        publishMessage(topic,message,1);
    }

    public static void batchCleanTopic(String productKey){
        //网关注册
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/request/request-id=0x10000001");
        //搜索设备
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000002");
        //添加设备
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000003");
        //删除设备
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000004");
        //删除相机
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000005");
        //修改设备
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000006");
        //获取设备列表
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000007");
        //获取相机列表
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000008");
        //获取设备信息
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000009");
        //获取相机信息
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x1000000a");


        //开始推流
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x20000001");
        //停止推流
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x20000005");


        //获取国标配置
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000001");
        //设置国标配置
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000002");
        //获取国标视频通道国标编码
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000003");
        //设置国标配置
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000004");


        //获取所有串口配置
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x40000001");
        //
        //获取串口配置
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x40000002");
        //设置串口
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x40000003");
        //

        //设置OTA
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x50000001");
        //上报OTA进度
        MqttUtils.cleanTopic("/sys/device/message/up/message-id=0x50000002");


        //获取黑名单
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000001");
        //修改黑名单
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000002");
        //删除黑名单
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000003");
        //添加黑名单
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000004");


        //上报正常车辆信息
//        MqttUtils.cleanTopic("/sys/device/message/up/message-id=0x60000001");
        MqttUtils.cleanTopic("/sys/device/"+productKey+"/event/up/event-id=0x10000001");
        //上报非法车辆信息
//        MqttUtils.cleanTopic("/sys/device/event/up/event-id=0x60000002");
    }

    public static void batchSubTopic(String productKey){
        //网关注册
        MqttUtils.subTopic("/sys/device/+/command/request/request-id=0x10000001");
        //搜索设备
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000002");
        //添加设备
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000003");
        //删除设备
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000004");
        //删除相机
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000005");
        //修改设备
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000006");
        //获取设备列表
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000007");
        //获取相机列表
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000008");
        //获取设备信息
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x10000009");
        //获取相机信息
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x1000000a");


        //开始推流
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x20000001");
        //停止推流
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x20000005");


        //获取国标配置
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000001");
        //设置国标配置
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000002");
        //获取国标视频通道国标编码
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000003");
        //设置国标配置
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x30000004");


        //获取所有串口配置
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x40000001");
        //
        //获取串口配置
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x40000002");
        //设置串口
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x40000003");
        //

        //设置OTA
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x50000001");
        //上报OTA进度
        MqttUtils.subTopic("/sys/device/message/up/message-id=0x50000002");


        //获取黑名单
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000001");
        //修改黑名单
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000002");
        //删除黑名单
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000003");
        //添加黑名单
        MqttUtils.subTopic("/sys/device/"+productKey+"/command/response/request-id=0x60000004");


        //上报正常车辆信息
//        MqttUtils.subTopic("/sys/device/message/up/message-id=0x60000001");
        MqttUtils.subTopic("$queue//sys/device/"+productKey+"/event/up/event-id=0x10000001");
//        //上报非法车辆信息
//        MqttUtils.subTopic("/sys/device/event/up/event-id=0x60000002");
    }
}
